

build_proj() {
    cd $PROJECT_PATH

    # get all .cpp files
    CSRC_LIST=`find $PROJECT_PATH/$CSRC_FOLDER -name "*.cpp"`
    for CSRC_FILE in ${CSRC_LIST[@]}
    do
        CSRC_FILES="$CSRC_FILES $CSRC_FILE"
    done
    # get all vsrc subfolders
    VSRC_SUB_FOLDER=`find $VSRC_FOLDER -type d`
    for SUBFOLDER in ${VSRC_SUB_FOLDER[@]}
    do
        INCLUDE_VSRC_FOLDERS="$INCLUDE_VSRC_FOLDERS -I$SUBFOLDER"
    done
    # get all csrc subfolders
    CSRC_SUB_FOLDER=`find $PROJECT_PATH/$CSRC_FOLDER -type d`
    for SUBFOLDER in ${CSRC_SUB_FOLDER[@]}
    do
        INCLUDE_CSRC_FOLDERS="$INCLUDE_CSRC_FOLDERS -I$SUBFOLDER"
    done


    # compile
    mkdir $BUILD_FOLDER 1>/dev/null 2>&1
    eval "verilator --x-assign unique --cc --exe --trace --assert -O3 -CFLAGS \"-std=c++11 -Wall $INCLUDE_CSRC_FOLDERS \"  -o $PROJECT_PATH/$BUILD_FOLDER/$EMU_FILE \
        -Mdir $PROJECT_PATH/$BUILD_FOLDER/emu-compile $INCLUDE_VSRC_FOLDERS --build $V_TOP_FILE $CSRC_FILES"
    if [ $? -ne 0 ]; then
        echo "Failed to run verilator!!!"
        exit 1
    fi

    cd $OSCPU_PATH
}

VSRC_FOLDER="vsrc"
CSRC_FOLDER="csrc"
BUILD_FOLDER="build_test"
EMU_FILE="emu"


OSCPU_PATH=$(dirname $(readlink -f "$0"))

PROJECT_FOLDER="puf"
V_TOP_FILE="top.v"

PROJECT_PATH=$OSCPU_PATH/projects/$PROJECT_FOLDER
BUILD_PATH=$PROJECT_PATH/$BUILD_FOLDER

BUILD="false"
SIMULATE="false"
GDB="false"
CLEAN="false"
PARAMETERS=

while getopts 'bsga:e:t:' OPT; do
    case $OPT in
        b) BUILD="true";;
        s) SIMULATE="true";;
        g) GDB="true";;
        c) CLEAN="true";;
        a) PARAMETERS="$OPTARG";;
        e) PROJECT_FOLDER="$OPTARG";;
        t) V_TOP_FILE="$OPTARG";;
    esac
done

# Clean
if [[ "$CLEAN" == "true" ]]; then
    rm -rf $BUILD_PATH
    exit 0
fi



# Build
if [[ "$BUILD" == "true" ]]; then
    cd ./chisel-template
    ./build.sh
    cd ..
    build_proj
fi

# Simulate
if [[ "$SIMULATE" == "true" ]]; then
    cd $BUILD_PATH

    # create soft link ($BUILD_PATH/*.bin -> $OSCPU_PATH/$BIN_FOLDER/*.bin). Why? Because of laziness!
    # create_soft_link $BUILD_PATH $OSCPU_PATH/$BIN_FOLDER \"*.bin\"

    # run simulation program
    echo "Simulating..."
    [[ "$GDB" == "true" ]] && gdb -s $EMU_FILE --args ./$EMU_FILE $PARAMETERS || ./$EMU_FILE $PARAMETERS

    if [ $? -ne 0 ]; then
        echo "Failed to simulate!!!"
        FAILED="true"
    fi

    cd $OSCPU_PATH
fi